//We start with the functions
YAHOO.namespace("draftrack.fop");

YAHOO.draftrack.fop.functions = function() {


	return { 
		
	functionsJSON:'',
	FoplineData:'',
	
	rendering : function() {
//console.log('rendering functions');

		renderString = '<ul>';
		
		//We render the different functions
		for(var i= 0; i < this.functionsJSON.length;i++) {
			functionDetails	= 	this.functionsJSON[i];	
			renderString += '<li>'+	this.renderFunction(functionDetails) + '</li>';
		}
		renderString += '</ul>';

		//We get the div where it should be displayed
		renderDivName = document.getElementById('js_functionsRenderDivId').innerHTML;
		renderDiv = document.getElementById(renderDivName);
		
		//We fill it with the data		
		renderDiv.innerHTML = 	renderString;
	},
	
	//this function render a node of function
	renderFunction: function(details) {
//console.log('rendering function');
//console.log(details);
		
		var fline = '';
		
		fline += '<div class="function" id="function_'+details.id+'">';
		fline += '<div id="functionDescription_'+details.id+'" class="functionDescription">'+details.description+'</div>';
		fline += '<input type="checkbox" id="functionCheckBox_'+details.id+'" name="functionSelected_'+details.id+'" ';
		
		//We check if the function is used in the FOPLine
		var fopLineFunctions = this.FoplineData.message.functions;
		var functionslength =fopLineFunctions.length;
		if(functionslength > 0) {
			for(var i = 0;i<functionslength;i++ ) {
				if(fopLineFunctions[i].id == details.id) {
					fline += 'checked';
					var value = (fopLineFunctions[i].structureData)?fopLineFunctions[i].structureData:'';
					
					//console.log(details.id+'-'+value);
					break;
				}
			}	
		}
		
		fline += ' ></input>';
		fline += '<span class="functionDescriptionMark" id="functionDescriptionMark_'+details.id+'">?</span>';
		fline += '<label for="functionCheckBox_'+details.id+'">'+details.shortName+' </label>';
		
		if(details.type == 'set') {
			fline += '<select id="functionStructureData_'+details.id+'" name="functionStructureData_'+details.id+'">';
			for(var i=0;i < details.structure.length;i++) {
					fline += '<option value="'+details.structure[i]+'" ';
					if(value == details.structure[i]) fline += 'selected';
					fline += ' >'+details.structure[i]+'</option>';
			}
			fline +='</select>';	
		}

		if(details.type == 'data') {
			var valueRepresentation = (value)?value:'';
			fline += '<input type="text" id="functionStructureData_'+details.id+'" name="functionStructureData_'+details.id+'" maxlength="'+details.structure.maxLength+'" size="'+details.structure.maxLength+'" value="'+ valueRepresentation +'"></input>';	
		}
		
		fline += '</div>';
		
		return fline;
	},

	toggleDescriptionBox:function (e) {
		var Box = YAHOO.util.Event.getTarget(e);
		//we extract the id
		//boxId = functionDescriptionMark_
		var id =Box.id.substr(24);
		
		//we get the description
		var description = document.getElementById('functionDescription_'+id);
		
		
		if(description.style.display == 'block') {
			description.style.display = 'none';	
		} else description.style.display = 'block';

		//We position the box
		var x = YAHOO.util.Dom.getX(Box); 	    var y = YAHOO.util.Dom.getY(Box); 		YAHOO.util.Dom.setX( description, x);		YAHOO.util.Dom.setY( description, y+15);

	},
	
	/*returns the data the user selected and returns it in JSON format */
	getJSONData: function() {
		//We go through the variables and check the ones we are interested in
		//We render the different functions
		var JSONString = new Array();
		for(var i= 0; i < this.functionsJSON.length;i++) {
			functionDetails	= 	this.functionsJSON[i];	
			var temp = this.getDataFunction(functionDetails);
			if(temp !=null ) JSONString.push(temp);
		}
		
		var MessageDefinition = '[';
		MessageDefinition += JSONString.join(",");
		MessageDefinition += ']';
		//console.log(MessageDefinition);
		return MessageDefinition;
				
	},	
	
	getDataFunction : function(details) {
//console.log('retrieving data for function');
//console.log(details);
		//We check if the 	box is selected
		var checkbox = document.getElementById('functionCheckBox_'+details.id);
		//If the checkbox is not checked, the user doesn t want to select the function
		if(!checkbox.checked) 	return;
		var structure = '';
		if(details.type == 'set') {
			structure	= document.getElementById('functionStructureData_'+details.id).value;
		}
		if(details.type == 'data') {
			structure	= document.getElementById('functionStructureData_'+details.id).value;
			if(structure.length > details.structure.maxLength || structure.length < details.structure.minLength) {
				alert('error: ' + details.shortName + ' must be between '+ details.structure.minLength + ' and '+details.structure.maxLength+' characters. This function will not be saved');
				return;
			}
		}
		if(details.type == 'string') return '{"id": "' + details.id + '"}';
			
		return '{"id": "' + details.id + '","structureData": "' + structure +'" }';
	},


	//initialisation of the parameters
	init : function(){
		//We collect the different functions available
		this.functionsJSON = YAHOO.lang.JSON.parse(document.getElementById('js_functionsData').innerHTML);
		this.FoplineData = YAHOO.lang.JSON.parse(document.getElementById('js_FoplineData').innerHTML);
		
		//We render the functions
//console.log('calling rendering');
		this.rendering();
		
		//We load the javascript events for the description boxes
		var elems = YAHOO.util.Dom.getElementsByClassName('functionDescriptionMark', 'span');
		YAHOO.util.Event.addListener(elems, "click", YAHOO.draftrack.fop.functions.toggleDescriptionBox);

				
	
	}//end init
	}; 
}();

//Event to get the data from the HTML page
YAHOO.util.Event.onDOMReady(YAHOO.draftrack.fop.functions.init,'',YAHOO.draftrack.fop.functions);












//Contain the JSON definition of the message 
var data;


YAHOO.widget.Logger.enableBrowserConsole();


function showHideSection(divId) {
var div = document.getElementById(divId);	
if(div.style.display == "none") {
	div.style.display = '';
	document.getElementById(divId + 'ShowHideSectionBox').className = 'hideSection';
}	
else {
	div.style.display = 'none';
	document.getElementById(divId + 'ShowHideSectionBox').className = 'showSection';
}
}

function initData() {
    data = YAHOO.lang.JSON.parse(document.getElementById('js_FoplineData').innerHTML);
YAHOO.log(data);
}


function outputTreeInit() { 
outputTree = new YAHOO.drafTrack.tableTree("treeOutput",oOutputConfigs);
outputTree.loadNodesData(nodesList); var root = outputTree.getRoot(); 
//issue the tree expect the value to be a string and we have a JSON object, need to stringify
YAHOO.log(data.message.structure);
if(data.message.structure.length > 0) {
	YAHOO.log('stringification starting');
	var stringified = stringifyValues(data.message.structure);
	YAHOO.log('stringification performed');
	YAHOO.log(stringified);
}
outputTree.loadNodes(stringified,root);
outputTree.draw(); 

}

function stringifyValues(data) {
	if(data.length > 0) {
		for(var i=0;i<data.length;i++) {
			data[i].values = YAHOO.lang.JSON.stringify(data[i].values);
			if(data[i].child) data[i].child = stringifyValues(data[i].child);
		}
	}
	return data;
}

	


YAHOO.util.Event.onDOMReady(initData);
YAHOO.util.Event.onDOMReady(outputTreeInit); 








///////////////////////////////////Nodes addition///////////////////////////////////

//Function to add a new input node to the list of nodes


	
function addOutputNode(structureElementName,displayName)
{	
	var objetArray = new Array();
	objetArray[0] = new Object();
	objetArray[0].displayName = displayName;
	objetArray[0].name = structureElementName;
	objetArray[0].values = '';	
	//Add the Node to the tree
	YAHOO.log(objetArray);
	var root = outputTree.getRoot(); 
	outputTree.loadNodes(objetArray,root);
	outputTree.draw(); 
	hideStructureSelector();
	
}





function selectStructureNode() {
	if(document.getElementById('structureeditor') === null) initStructureSelector();
	displayStructureSelector();
}

function initStructureSelector() {
	// Attach Cell Editor container element as first child of body
	var elStructureEditor = document.createElement("div");
	elStructureEditor.id = "structureeditor";
	elStructureEditor.style.display = "none";
	elStructureEditor.style.position = "absolute";
	elStructureEditor.tabIndex = 0;
	Dom.addClass(elStructureEditor, 'structureEditor');
	
	var string ='<div id="structureeditor-widget">';
	
	var structureElements = nodesList.nodes;
	for(var i=0;i<structureElements.length;i++) {
		//Some elements (like the group element) should not be displayed in the list
		if(structureElements[i].doNotDisplay && structureElements[i].doNotDisplay) continue;
		string += '<button onclick="addOutputNode(\''+structureElements[i].name+'\',\''+structureElements[i].displayName+'\')">'+structureElements[i].displayName +'</button>';
	}
	
	
	string += '</div><div class="buttons_group"><button onclick="javascript:hideStructureSelector()">Cancel</button></div>';
	
	elStructureEditor.innerHTML = string;
	
	//Dom.addClass(elCellEditor, DT.CLASS_EDITOR);
	var elFirstChild = Dom.getFirstChild(document.body);
	if(elFirstChild) {
	elCellEditor = Dom.insertBefore(elStructureEditor, elFirstChild);
	}
	else {
	document.body.appendChild(elStructureEditor);
	}
}




function hideStructureSelector() {
	document.getElementById('structureeditor').style.display = 'none';
}

function displayStructureSelector() {
	//we position the selector
	var x = YAHOO.util.Dom.getX('selectStructureNodeButton');
	var y = YAHOO.util.Dom.getY('selectStructureNodeButton');
	var selector = document.getElementById('structureeditor');

	selector.style.left = x + "px";
    selector.style.top = y + "px";
	selector.style.display = 'block';
	selector.style.zindex = 999;
}



function addOutputGroup()
{

	var objetArray = new Array();
	objetArray[0] = new Object();
	objetArray[0].displayName = "aim of the group";
	objetArray[0].name = "group";
	objetArray[0].values = '';	
	objetArray[0].child = new Array();
	objetArray[0].child[0] = new Object();
	objetArray[0].child[0].displayName = "string";
	objetArray[0].child[0].name = "string";
	objetArray[0].child[0].values = '';	
	
	
	//Add the Node to the tree
	var root = outputTree.getRoot(); 
	outputTree.loadNodes(objetArray,root);
	outputTree.draw(); 
}




///////////////////////////////////Nodes addition///////////////////////////////////

function getMessageDefinition()
{
	//input definition
	var MessageDefinition = '{"structure":';
	MessageDefinition += outputTree.getTreeJSONData();
	
	//output definition
	MessageDefinition += ',"functions":';
	MessageDefinition += YAHOO.draftrack.fop.functions.getJSONData();	
	
	
	
	MessageDefinition += '}';
	
	return MessageDefinition;
	
}








